<?php

namespace app\admin\logic\system;

use app\admin\logic\BaseLogic;
use app\common\model\SystemRegion;
use app\common\exception\ApiException;
use app\common\utils\Arr;
use app\common\utils\Helper;
use Overtrue\Pinyin\Pinyin;

/**
 * 地区逻辑层
 */
class SystemRegionLogic extends BaseLogic
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new SystemRegion();
        $this->defaultSort = ['adcode' => 'asc', 'id' => 'asc'];
    }

    /**
     * 数据添加
     */
    public function add($data): mixed
    {
        $data = $this->handleData($data);
        return $this->model->save($data);
    }

    /**
     * 数据修改
     */
    public function edit($id, $data): mixed
    {
        $data = $this->handleData($data);
        if ($data['parent_id'] == $id) {
            throw new ApiException('不能设置父级为自身');
        }
        return $this->model->update($data, ['id' => $id]);
    }

    /**
     * 数据删除
     */
    public function destroy($ids)
    {
        $num = $this->model->where('parent_id', 'in', $ids)->count();
        if ($num > 0) {
            throw new ApiException('该地区下存在子地区，请先删除子地区');
        } else {
            return $this->model->destroy($ids);
        }
    }

    /**
     * 数据处理
     */
    protected function handleData($data)
    {
        if (empty($data['parent_id']) || $data['parent_id'] == 0) {
            $data['level'] = 1;
            $data['parent_id'] = 0;
        } else {
            $regionList = $this->model->findOrEmpty($data['parent_id']);
            $data['level'] = $regionList['level'] + 1;
        }
        if ((empty($data['initial']) || empty($data['pinyin'])) && !empty($data['name'])) {
            $pinyin = new Pinyin();
            if (empty($data['initial'])) {
                $data['initial'] = str_replace(' ', '', $pinyin->abbr($data['name'], '') ?? '');
            }
            if (empty($data['pinyin'])) {
                $data['pinyin'] = $pinyin->permalink($data['name'], '') ?? '';
            }
        }
        return $data;
    }

     public function getAllRegion($where = [])
    {
        $query = $this->search($where);
        $query->field('*, id as value, name as label');
        $data = $this->getAll($query);
        return $data;
    }
}